<?php

/**
 * 特批授权服务
 * @author yuzy 2015-5-7
 */

namespace common\services\myhtsq;

use common\services\BaseService;
use common\error\ErrorCode;
use common\entities\ConfigEntity;
use common\repositories\myhtsq\SpecialApprovalAuthorizeRepository;
use common\models\myhtsq\SpecialApprovalAuthorizeModel;
use common\services\myhtsq\DocumentService;
use common\support\PageParam;
use common\models\myhtsq\DocumentModel;
use common\support\StringHelper;
use common\services\myhtsq\ContractService;

class SpecialApprovalAuthorizeService extends BaseService {

    protected $_authorizeRepository;
        
    /**
     * 构造函数
     */
    public function __construct(SpecialApprovalAuthorizeRepository $authorizeRepository) {
        $this->_authorizeRepository = $authorizeRepository;        
    }

    /**
     * 特批授权列表
     * @param integer $page 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @return array
     */
    public function getSpecialApprovalAuthorizeList($pageIndex, $pageSize, $sortBy, $sortAsc, $keyword, $areaId,$fulfil) {
        $pageParam = new PageParam($pageIndex, $pageSize, $sortBy, $sortAsc);

        #区域过滤
        if(empty($areaId)) {
           $areaId = ContractService::filterBusinessUnit(\Yii::$app->user->identity);
        }
        $now = ConfigEntity::getDbNowDate();
        
        $result = SpecialApprovalAuthorizeRepository::getSpecialApprovalAuthorizeList($pageParam, $areaId, $fulfil, $keyword);
        $contractService = new ContractService();
        $erpInterfaceService = new ErpInterfaceService();
        foreach ($result['items'] as $key => $value) {
            $applications = $contractService->getContractOrganizationInfo($value['contract_id']);
            $order_code = $delivery_guid = $authProductName = '';
            if($value['erp_contract_code']){
               $data = $erpInterfaceService->GetDeliveryList(1,1,$value['erp_contract_code']);
               $deliveryInfos = $data['data'];
               $rows = $deliveryInfos->rows;
               $deliveryInfo = $rows[0];
               $order_code = $deliveryInfo->order_code;
               //有出库单号的去出库的产品名称
               if (!empty($order_code)) {
                   $delivery_guid = $deliveryInfo->delivery_guid;
                   $deliveryDetail = $erpInterfaceService->GetDeliveryDetail($delivery_guid);
                   $deliveryDetail = json_decode(json_encode($deliveryDetail), true);
                   if(!empty($deliveryDetail['data']['YlInfo']['Yl_Tenant'][0]['Erp_Products'])){
                       foreach ($deliveryDetail['data']['YlInfo']['Yl_Tenant'][0]['Erp_Products'] as $pro) {
                           $authProductName .= '【'.$pro['Product_Name'].'】';
                       }
                   }
               } else {
                   $authProductName = $value['authproduct_name'];
               }
            }
            $result['items'][$key]['order_code'] = $order_code;
            $result['items'][$key]['order_guid'] = $delivery_guid;
            $result['items'][$key]['authProductName'] = $authProductName;
            if($applications ===FALSE){
                $applications = [];
            }
            $result['items'][$key]['applications'] = $applications;
            $days=floor((strtotime($result['items'][$key]['promise_fulfil_time']) - strtotime($now))/86400);
            if(empty($result['items'][$key]['actual_fulfil_time'])){
                $result['items'][$key]['days'] = $days;
            }else{
                $result['items'][$key]['days'] = 0;
            }
            unset($result['items'][$key]['specialAuthorize']);
        }
        $this->setAndReturn(ErrorCode::SUCCESS);
        return $result;
    }

    /**
     * 获取特批授权信息
     * @param string $invoiceId
     * @return \common\models\myhtsq\SpecialApprovalAuthorizeModel
     */
    public function getSpecialApprovalAuthorizeInfo($invoiceId) {
        $entity = SpecialApprovalAuthorizeRepository::getSpecialApprovalAuthorizeInfo($invoiceId);
        $list = DocumentService::getDocumentListByBusinessId($invoiceId);

        $authProductName = $entity['authproduct_name'];
        if($entity['erp_contract_code']){
            $erpInterfaceService = new ErpInterfaceService();
            $data = $erpInterfaceService->GetDeliveryList(1,1,$entity['erp_contract_code']);
            $deliveryInfos = $data['data'];
            $rows = $deliveryInfos->rows;
            $deliveryInfo = $rows[0];
            $order_code = $deliveryInfo->order_code;
            //有出库单号的取出库的产品名称
            if (!empty($order_code)) {
                $delivery_guid = $deliveryInfo->delivery_guid;
                $deliveryDetail = $erpInterfaceService->GetDeliveryDetail($delivery_guid);
                $deliveryDetail = json_decode(json_encode($deliveryDetail), true);
                if(!empty($deliveryDetail['data']['YlInfo']['Yl_Tenant'][0]['Erp_Products'])){
                    foreach ($deliveryDetail['data']['YlInfo']['Yl_Tenant'][0]['Erp_Products'] as $pro) {
                        $authProductName .= '【'.$pro['Product_Name'].'】';
                    }
                }
            }
        }
        $entity['authproduct_name'] = $authProductName;
        $result['item'] = $entity;
        $result['attachmentList'] = $list;
        return $result;
    }

    /**
     * 新增特批授权
     * @param \common\models\myhtsq\SpecialApprovalAuthorizeModel $authorizeModel
     * @return boolean|string   失败|合同Guid
     */
    public function addSpecialApprovalAuthorize($authorizeModel, $attachmentList) {
        if ($authorizeModel->validate()) {
            $result = $this->_authorizeRepository->addSpecialApprovalAuthorize($authorizeModel);
            if ($result === FALSE) {
                return $this->setAndReturn($this->_authorizeRepository->getErrCode());
            } else {
                // 附件
                $documentService = new DocumentService();
                foreach ($attachmentList as $idx => $value) {
                    $documentModel = new DocumentModel();
                    $documentModel->load($value,'');
                    $documentModel->document_id = StringHelper::uuid();
                    $documentModel->document_ext_name = StringHelper::getFileExtName($documentModel->document_path);
                    $documentModel->business_id = $result;
                    $documentService->addDocument($documentModel);
                }
                return $result;
            }
        } else {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_FORM_VERIFY_FAIL);
        }
    }

    /**
     * 更新特批授权
     * @param \common\models\myhtsq\SpecialApprovalAuthorizeModel $authorizeModel
     * @return boolean|string   失败|合同Guid
     */
    public function updateSpecialApprovalAuthorize($authorizeModel, $attachmentList) {
        if ($authorizeModel->validate()) {
            $result = $this->_authorizeRepository->updateSpecialApprovalAuthorize($authorizeModel);
            if ($result === FALSE) {
                return $this->setAndReturn($this->_authorizeRepository->getErrCode());
            } else {
                // 原附件列表
                $originalDocumentList = DocumentService::getDocumentListByBusinessId($authorizeModel->special_approval_authorize_id);
                $documentService = new DocumentService();

                foreach ($originalDocumentList as $idx => $value) {
                    $hit = false;
                    foreach ($attachmentList as $idx2 => $value2) {
                        if ($value['document_id'] == $value2['document_id']) {
                            $hit = true;
                            break;
                        }
                    }
                    if ($hit === false) {
                        $documentService->delDocumentById($value['document_id']);
                    }
                }

                foreach ($attachmentList as $idx => $value) {
                    $hit = false;
                    foreach ($originalDocumentList as $idx2 => $value2) {
                        if ($value['document_id'] == $value2['document_id']) {
                            $hit = true;
                            break;
                        }
                    }                    
                    if ($hit === false) {
                        $documentModel = new DocumentModel();
                        $documentModel->load($value,'');
                        $documentModel->document_id = StringHelper::uuid();
                        $documentModel->document_ext_name = StringHelper::getFileExtName($documentModel->document_path);
                        $documentModel->business_id = $authorizeModel->special_approval_authorize_id;
                        $documentService->addDocument($documentModel);
                    }                    

                }
                return $result;
            }
        } else {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_FORM_VERIFY_FAIL);
        }
    }
    
    /**
     * 导出特批授权
     * @param type $data
     */
    public function exportSpecialApprovalAuthorizeList ($data) {
        if (isset($data) && count($data) > 0) {
            $CategoryList = [
                1 => '合同未归档',
                2 => '首期款未回',
                3 => '授权信息与合同信息不一致',
                4 => '合同扫描件未提供',
                5 => '结算款未支付',
                6 => '其他',
                7 => '合同未归档,首期款未回'
            ];
            foreach ($data as $k => $v) {
                $category = $v['category'];
                $data[$k]['category_name'] = '';
                if (!is_null($category) && isset($CategoryList[$category])) {
                    $data[$k]['category_name'] = $CategoryList[$category];
                    continue;
                }
            }
        }
        $objPHPExcel = new \PHPExcel();
        //设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        //设置单元格的值
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '特批授权id');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '租户名称');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '特批类型');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '兑现责任人');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '承诺日期');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '兑现日期');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '备注');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '合同编号');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '合同所属区域');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '出库单号');

        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['special_approval_authorize_id']); // 发票id
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['organization_name']); // 租户名称
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['category_name']); //特批类型
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['principal_name']); //兑现责任人
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, empty($val['promise_fulfil_time']) ? "" : date('Y-m-d', strtotime($val['promise_fulfil_time']))); //承诺日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, empty($val['actual_fulfil_time']) ? "" : date('Y-m-d', strtotime($val['actual_fulfil_time']))); //兑现日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['comment']); //摘要
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['area_name']); //合同签署公司
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['order_code']); //出库单号
                $j++;
            }
        }
        
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setVisible(false); //把授权guid 设置为隐藏列
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="特批授权' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 读取负责人所在区域
     */
    public function getPromiseFulfilArealist(){
        $sql = 'SELECT b.BUName areaName,b.BUGUID areaId FROM myscrm_special_approval_authorize a
                inner join myscrm_erp_business_unit b on a.promise_fulfil_areaid=b.BUGUID
                GROUP BY b.BUName,b.BUGUID';

        $data = ConfigEntity::getDb()->createCommand($sql)->queryAll();
        return $data;
    }
}
